package top.lixunda.common.validate.validate;

import top.lixunda.common.validate.annotation.XumBetweenDouble;
import top.lixunda.common.validate.core.ValidateError;
import top.lixunda.common.validate.exception.XumValidException;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @author Xumda
 * @version time:2019/12/9 13:15
 */
public class BetweenDoubleValidate implements AnnotationValidate {

    @Override
    public boolean support(Class annotationClass) {
        return XumBetweenDouble.class.equals(annotationClass);
    }

    @Override
    public ValidateError valid(Annotation annotation, Field field, Object obj, Object value, AnnotationCacheValidate handler) {
        // 获取值
        XumBetweenDouble a = (XumBetweenDouble) annotation;
        double max = a.max(), min = a.min();
        boolean include = a.include();
        String message = a.message();

        boolean isNull = (value == null || (value instanceof String && "".equals(value)));
        if (isNull) {
            return null;
        }

        if (value instanceof Float || value instanceof Double) {
            double i = ValidatorPrivateUtils.getDoubleFromNumber(value);
            if (!((a.include() ? i <= max : i < max) && (a.include() ? i >= min : i > min))) {
                return new ValidateError(getErrorMessage(message, include, field, i, min, max));
            }
        } else {
            throw new XumValidException("XumBetweenDouble");
        }
        return null;
    }

    private String getErrorMessage(String message, boolean include, Field field, double value, Object min, Object max) {
        return "".equals(message)
                ? field.getName() + "应大于" + (include ? "等于" : "") + String.valueOf(min) + "且小于" + (include ? "等于" : "") + String.valueOf(max)
                : message.replaceAll("#value#", String.valueOf(value)).replaceAll("#name#", field.getName());
    }

}
